package com.test.videoplayer.activity.rabbit;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.TextView;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.test.videoplayer.R;

@SuppressLint("Registered")
public class RabbitActivity extends AppCompatActivity {

    private TextView showMessageTv;
    private StringBuilder sb = new StringBuilder();
    private final String exchangeName = "test.topic";
    private final String receiveQueue = "test_queue_topic_topic2";
    //自己配置发送接受队列名称和绑定key
    private final static String EXCHANGE_NAME = "test_exchange_topic1";
    private final static String QUEUE_NAME = "test_queue_topic_topic1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_connect);
        showMessageTv = findViewById(R.id.txtrabbitmqt);
        showMessageTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        RabbitMQUtil.initService("192.168.0.213", 5672, "admin", "admin");
    }

    @SuppressLint("SetTextI18n")
    private void getDadaMq() {
        RabbitMQUtil.getInstance().receiveQueueMessage(receiveQueue, message -> {
            Log.d("Tag", "message : " + message);
          /*  try {
                JSONObject jsonObject = new JSONObject(message);
                JSONObject jsonHead = jsonObject.getJSONObject("header");
                JSONObject jsonMsgBodyProperty = jsonHead.getJSONObject("msgBodyProperty");
                int protocolVersion = jsonMsgBodyProperty.getInt("protocolVersion");
                String terminalPhoneNo = jsonHead.getString("terminalPhoneNo");
                JSONObject jsonBody = jsonObject.getJSONObject("body");
                String datetime = jsonBody.getString("datetime");
                Log.d("Tag","datetime:" + datetime);
                //sb.append("收到了queue消息：").append(message).append("\n");
                runOnUiThread(() -> showMessageTv.setText("刷新请求时间:" + datetime));
            } catch (JSONException e) {
                e.printStackTrace();
            }*/
        });
    }


    public void sendInsert(View view) throws Exception {
        // Log.d("Tag", "message :【添加】");
        // 获取到连接以及mq通道
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        // 声明exchange
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        // 消息内容
        String message = "Hello World!【添加】";
        channel.basicPublish(EXCHANGE_NAME, "item.insert", null, message.getBytes());
        channel.close();
        connection.close();
    }

    public void sendDelete(View view) throws Exception {
        //Log.d("Tag", "message :【删除】");
        // 获取到连接以及mq通道
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        // 声明exchange
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        // 消息内容
        String message = "Hello World!【删除】";
        channel.basicPublish(EXCHANGE_NAME, "item.delete", null, message.getBytes());
        channel.close();
        connection.close();
    }

    public void sendUpdate(View view) throws Exception {
        //Log.d("Tag", "message :【修改】");
        // 获取到连接以及mq通道
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        // 声明exchange
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        // 消息内容
        String message = "Hello World!【修改】";
        channel.basicPublish(EXCHANGE_NAME, "item.update", null, message.getBytes());
        channel.close();
        connection.close();
    }

    public void sendALL(View view) throws Exception {
        //Log.d("Tag", "message :【修改】");
        // 获取到连接以及mq通道
        Connection connection = getConnection();
        Channel channel = connection.createChannel();
        // 声明exchange
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        // 消息内容
        String message = "Hello World!【所有】";
        channel.basicPublish(EXCHANGE_NAME, "item.delete", null, message.getBytes());
        channel.basicPublish(EXCHANGE_NAME, "item.update", null, message.getBytes());
        channel.close();
        connection.close();
    }

    public void recv(View view) {
        new Thread(() -> {
            try {
                getDanyi();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    public void getDanyi() throws Exception {
        // 获取到连接以及mq通道
        Connection connection = getConnection();
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 绑定队列到交换机
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "item.update");
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "item.delete");

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        // 定义队列的消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 监听队列，手动返回完成
        channel.basicConsume(QUEUE_NAME, false, consumer);

        // 获取消息
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            Log.d("Tag", "recv1 :" + message + "'");
            Thread.sleep(10);
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }

    public void recv2(View view) {
        //开启消费者线程
        new Thread(this::getDadaMq).start();
    }

    public static Connection getConnection() throws Exception {
        // 定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置服务地址
        factory.setHost("192.168.0.213");
        // 端口
        factory.setPort(5672);
        // 设置账号信息，用户名、密码、vhost
        factory.setUsername("admin");
        factory.setPassword("admin");
        // 通过工程获取连接
        return factory.newConnection();
    }

    @Override
    protected void onDestroy() {
        RabbitMQUtil.getInstance().close();
        super.onDestroy();
    }
}
